import getUserTempId from "@/utils/userTempId";

import { 
  requestLogin,
  requestUserInfo,
  requestLogout
} from "@/api"

const state = {
  userTempId: getUserTempId(),
  token:localStorage.getItem('token') || '',
  userInfo:{
    nickName:'',
  }
}

const mutations = {
  SET_TOKEN_STATE(state,value){
    state.token = value
  },
  SET_USERINFO_STATE(state,value){
    state.userInfo.nickName = value
  },
  RESET_USERINFO_STATE(state){
    state.token = "",
    state.userInfo = { nickName:"" },
    localStorage.removeItem('token')
  }
}

const actions = {
  async getToken({commit}, userInfo){
    try{
      const res = await requestLogin(userInfo)
      commit('SET_TOKEN_STATE',res.token)
      // token存入本地
      localStorage.setItem('token', res.token)
    }catch(e){
      return Promise.reject(e);
    }
  },
  async getUserInfo({ commit }){
    try{
      const res = await requestUserInfo()
      /* 
      抛出错误
      */
      if(!res) throw new Error({message:'错误'})
      commit('SET_USERINFO_STATE',res.nickName)
    }catch(e){
      return Promise.reject({message:e.message})
    }
  },
  async getLogout({ commit }){
    await requestLogout()
    commit('RESET_USERINFO_STATE')
  }
}

/* const getters = {
  userInfo(state){
    return state.userInfo || {}
  }
}
 */

export default {
  namespaced:true,
  state,
  mutations,
  actions,
  // getters
}